import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import sys
import os

# 添加项目根目录到Python路径并导入配置
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
    from config import EMAIL_ENABLED, EMAIL_CONFIG
except ImportError:
    EMAIL_ENABLED = True
    EMAIL_CONFIG = {
        'smtp_server': 'smtp.qq.com',
        'smtp_port': 587,
        'sender_email': '',
        'sender_password': '',
        'receiver_email': '',
    }

class EmailSender:
    def __init__(self):
        # 邮箱配置从配置文件读取
        self.smtp_server = EMAIL_CONFIG['smtp_server']
        self.smtp_port = EMAIL_CONFIG['smtp_port']
        self.sender_email = EMAIL_CONFIG['sender_email']
        self.sender_password = EMAIL_CONFIG['sender_password']
        self.receiver_email = EMAIL_CONFIG['receiver_email']

    def send_email(self, subject, message):
        # 检查邮件发送开关
        if not EMAIL_ENABLED:
            print("邮件发送功能已关闭")
            return False
            
        try:
            # 创建邮件对象
            msg = MIMEMultipart()
            msg['From'] = Header(f"Notification <{self.sender_email}>")
            msg['To'] = Header(self.receiver_email)
            msg['Subject'] = Header(subject, 'utf-8')
            
            # 添加邮件正文
            msg.attach(MIMEText(message, 'plain', 'utf-8'))
            
            # 连接SMTP服务器并发送邮件
            server = smtplib.SMTP(self.smtp_server, self.smtp_port)
            server.starttls()
            server.login(self.sender_email, self.sender_password)
            server.send_message(msg)
            server.quit()
            
            print(f"邮件发送成功: {subject}")
            return True
        except Exception as e:
            print(f"邮件发送失败: {str(e)}")
            return False

def main():
    if len(sys.argv) < 2:
        print("使用方法: python email_sender.py [end|pending] [可选消息]")
        sys.exit(1)
    
    notification_type = sys.argv[1]
    custom_message = sys.argv[2] if len(sys.argv) > 2 else ""
    
    sender = EmailSender()
    
    if notification_type == "end":
        subject = "ClaudeCode 处理完成"
        message = custom_message if custom_message else "ClaudeCode 处理完成"
    elif notification_type == "pending":
        subject = "ClaudeCode 有待处理任务"
        message = custom_message if custom_message else "ClaudeCode 有待处理任务"
    else:
        print("参数错误: 请使用 'end' 或 'pending'")
        sys.exit(1)
    
    sender.send_email(subject, message)

if __name__ == "__main__":
    main()